package e.g;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.roundface.model.Tabel;
import org.roundface.util.ConnetionUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class MyGenerator {

	/**
	 * 
	 * @author Marvis
	 * @version 2014-12-6下午1:44:26
	 * @param tablesMap
	 *            map的key为表名,value为生成类名(aliasName) <br/>
	 *            "K_AMC_BEAUTIFY_CATEGORY", "BeautifyCategory"
	 * @param javaPackagePath
	 *            :java包路径
	 * @param mapperPackagePath
	 *            :mapper路径
	 * @throws Exception
	 */
	public void gener(Map<String, String> tablesMap, String javaPackagePath,
			String mapperPackagePath,String primaryKeyType) throws Exception {

		String[] types = { "TABLE" };
		@SuppressWarnings("deprecation")
		Configuration cfg = new Configuration();
		cfg.setClassForTemplateLoading(MyGenerator.class, "/templates");
		Connection jdbcConnection = ConnetionUtils.getConnetion();
		for (String table : tablesMap.keySet()) {
			List<Tabel> l = ConnetionUtils.getTables(jdbcConnection, types,
					table);
			for (Tabel t : l) {
				System.out.println(t.getTabelName());
				System.out.println("----------------------------");
				generateData(cfg, t, tablesMap.get(table), javaPackagePath,
						mapperPackagePath,primaryKeyType);
				// generateInterface(cfg, t, modelname);
				// generateListJsp(cfg, t, modelname);
			}
		}
	}

	public static void generateData(Configuration cfg, Tabel t,
			String aliasName, String javaPackagePath, String mapperPackagePath,String primaryKeyType)
			throws IOException, TemplateException {

		javaPackagePath = javaPackagePath
				+ (".".equals(javaPackagePath.charAt(javaPackagePath.length() - 1)) ? ""
						: ".");
		mapperPackagePath = mapperPackagePath
				+ (".".equals(mapperPackagePath.charAt(mapperPackagePath
						.length() - 1)) ? "" : ".");

		String jpp = javaPackagePath.replace(".", "/");
		String mpp = mapperPackagePath.replace(".", "/");

		/*************************entity*********************************/
		Template temp = cfg.getTemplate("model_temp.ftl");
		String outdir = getPath() + "/data/" + jpp + "entity";
		String outfile = aliasName + ".java";
		generate(aliasName, javaPackagePath, mapperPackagePath,primaryKeyType, t, temp,
				outfile, outdir);
		/*************************dao*********************************/
		Template temp2 = cfg.getTemplate("dao_temp.ftl");
		String outdir2 = getPath() + "/data/" + jpp + "dao";
		String outfile2 = aliasName + "Dao.java";
		generate(aliasName, javaPackagePath, mapperPackagePath,primaryKeyType, t, temp2,
				outfile2, outdir2);
		/*************************mapper*********************************/
		Template temp3 = cfg.getTemplate("mapper_temp.ftl");
		String outdir3 = getPath() + "/data/" + mpp ;
		String outfile3 = aliasName + "Mapper.xml";
		generate(aliasName, javaPackagePath, mapperPackagePath,primaryKeyType, t, temp3,
				outfile3, outdir3);
		/*************************controller*********************************/
		Template temp5 = cfg.getTemplate("controller_temp.ftl");
		String outdir5 = getPath() + "/data/" + jpp + "controller";
		String outfile5 = aliasName + "Controller.java";
		generate(aliasName, javaPackagePath, mapperPackagePath,primaryKeyType, t, temp5,
				outfile5, outdir5);
		/*************************service*********************************/
		Template temp6 = cfg.getTemplate("service_temp.ftl");
		String outdir6 = getPath() + "/data/" + jpp + "service";
		String outfile6 = aliasName + "Service.java";
		generate(aliasName, javaPackagePath, mapperPackagePath,primaryKeyType, t, temp6,
				outfile6, outdir6);
		/*************************serviceImpl*********************************/
		Template temp7 = cfg.getTemplate("serviceImpl_temp.ftl");
		String outdir7 = getPath() + "/data/" + jpp + "service/impl";
		String outfile7 = aliasName + "ServiceImpl.java";
		generate(aliasName, javaPackagePath, mapperPackagePath,primaryKeyType, t, temp7,
				outfile7, outdir7);
	}

	public static void 
	generateInterface(Configuration cfg, Tabel t,
			String domain) throws IOException, TemplateException {

		Template temp2 = cfg.getTemplate("controller_temp.ftl");
		String outdir2 = getPath() + "/" + domain + "/controller";
		String outfile2 = t.getClassName() + "Controller.java";
		generate(domain, t, temp2, outfile2, outdir2);

		Template temp3 = cfg.getTemplate("service_temp.ftl");
		String outdir3 = getPath() + "/" + domain + "/service";
		String outfile3 = t.getClassName() + "Service.java";
		generate(domain, t, temp3, outfile3, outdir3);

		Template temp4 = cfg.getTemplate("serviceImpl_temp.ftl");
		String outdir4 = getPath() + "/" + domain + "/service/impl";
		String outfile4 = t.getClassName() + "ServiceImpl.java";
		generate(domain, t, temp4, outfile4, outdir4);

	}

	public static void generateListJsp(Configuration cfg, Tabel t, String domain)
			throws IOException, TemplateException {

		String path = getPath();
		Template temp = cfg.getTemplate("list_jsp_temp.ftl");
		String outdir = path + "/views/" + domain + "/" + t.getVarName() + "/";
		String outfile = "list.jsp";
		generate(domain, t, temp, outfile, outdir);

		Template temp1 = cfg.getTemplate("info_jsp_temp.ftl");
		String outfile1 = "info.jsp";
		generate(domain, t, temp1, outfile1, outdir);

		Template temp2 = cfg.getTemplate("form_jsp_temp.ftl");
		String outfile2 = "form.jsp";

		generate(domain, t, temp2, outfile2, outdir);
	}

	public static void generate(String domain, Tabel t, Template temp,
			String outfilename, String outdir) throws IOException,
			TemplateException {
		File f = new File(outdir);
		f.mkdirs();
		File fn = new File(f.getPath() + "/" + outfilename);
		fn.createNewFile();
		FileOutputStream fos = new FileOutputStream(fn);
		Writer out = new OutputStreamWriter(fos);
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("table", t);
		root.put("domain", domain);
		temp.process(root, out);
		out.flush();
		out.close();
	}

	public static void generate(String domain, String javaPackagePath,
			String mapperPackagePath,String primaryKeyType, Tabel t, Template temp,
			String outfilename, String outdir) throws IOException,
			TemplateException {
		File f = new File(outdir);
		f.mkdirs();

		File fn = new File(f.getPath() + "/" + outfilename);
		fn.createNewFile();
		FileOutputStream fos = new FileOutputStream(fn);
		Writer out = new OutputStreamWriter(fos);
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("table", t);
		root.put("domain", domain);
		root.put("domainLowerHead", Character.toLowerCase(domain.charAt(0)) + domain.substring(1, domain.length()));
		root.put("acccessPrefixPath", javaPackagePath.replace(".", "/").replace("com/an", ""));
		root.put("javaPackagePath", javaPackagePath); 
		root.put("mapperPackagePath", mapperPackagePath);
		root.put("primaryKeyType", primaryKeyType);
		temp.process(root, out);
		out.flush();
		out.close();
	}

	public static void generate(Tabel t, Template temp, String outfilename,
			String outdir) throws IOException, TemplateException {
		generate("", t, temp, outfilename, outdir);
	}

	public static String getPath() throws FileNotFoundException {
		String path = MyGenerator.class.getResource("/").getPath();
		// String path =
		// Thread.currentThread().getContextClassLoader().getResource("").toString();

		File s = new File(path).getParentFile();
		String n = s.getPath() + "/out/";
		File f = new File(n);
		if (f.exists()) {
			f.delete();
		}
		return f.getPath();

	}
}
